import Vue from 'vue'
import Layout from '@/views/layout'
import Category from '@/views/layout/category.vue'
import Home from '@/views/layout/home.vue'
import Cart from '@/views/layout/cart.vue'
import User from '@/views/layout/user.vue'
import VueRouter from 'vue-router'

import store from '@/store'
import { Toast } from 'vant'

const Login = () => import('@/views/login')
const MyOrder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')
const ProDetail = () => import('@/views/prodetail')
const Search = () => import('@/views/search/index.vue')
const SearchList = () => import('@/views/search/list.vue')
const EditMyInfo = () => import('@/views/my/editMyInfo.vue')
const addressEdit = () => import('@/views/my/addressEdit.vue')
const checklogistics = () => import('@/views/myorder/check.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login
    },
    {
      path: '/layout',
      component: Layout,
      children: [
        { path: '/home', component: Home },
        { path: '/category/:index', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }
      ]
    },
    { path: '/myorder', component: MyOrder },
    { path: '/checklogistics', component: checklogistics },
    { path: '/prodetail/:id', component: ProDetail },
    { path: '/search', component: Search },
    { path: '/pay', component: Pay },
    { path: '/searchlist', component: SearchList },
    { path: '/myinfo', component: EditMyInfo },
    { path: '/editaddress/:id', component: addressEdit },
    { path: '/', component: Layout, redirect: '/home' }
  ]
})

const authUrls = ['/myorder']

router.beforeEach((to, from, next) => {
  // if (to.meta && to.meta.requireSpecificFrom) {
  //   const isAllowed = to.meta.requireSpecificFrom.some(allowedPath => {
  //     if (allowedPath.includes(':id')) {
  //       return from.path.startsWith(allowedPath.replace(':id', ''))
  //     }
  //     return from.path === allowedPath
  //   })
  //   if (!isAllowed) {
  //     Toast('请从购物车或商品详情页进入支付页面')
  //     next('/home')
  //   } else {
  //     next()
  //   }
  // }
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  const token = store.getters.token
  if (token) {
    next()
  } else {
    Toast('请先登录')
    next('/login')
  }
})

export default router
